/* $RCSFile: DefaultModulesPage.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/Secure/DefaultModulesPage.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:44:00  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Authentication;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.Secure
{
	/// <summary>
	/// The DefaultModulesPage.aspx page is used 
	/// to load and populate each Portal View.
	/// It accomplishes this by reading the layout configuration 
	/// of the portal from the Portal Configuration	system, 
	/// and then using this information to dynamically 
	/// instantiate portal modules (each implemented 
	/// as an ASP.NET User Control), and then inject them into the page.
	/// </summary>
	public partial class DefaultModulesPage : DefaultCRMPage
	{
        protected override void Add2PlaceHolder(Control c)
        {
            LayoutPlaceHolder.Controls.Add(c);
        }
        /*
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage Page_Load portalSettings.ActivePageSettings: {0}.", portalSettings.ActivePageSettings.PageName),PageTraceSwitch.Sw.Info);
            // CS 24/10/04 triggers a PageRequest event
            // placed here to trigger an exception if CRM is not correctly installed 
            try
            {
                if (AuthenticationTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage Page_Load portalID: {0}, CurrentUser null: {1}, CurrentUserADNCRMPrincipal: {2}, AuthenticationMode: {3}.", 
                        new object[] {portalSettings.PortalID, PortalSettings.IsCurrentUserNull, PortalSettings.IsCurrentUserADNCRMPrincipal,Config.AuthenticationMode} ),
                        AuthenticationTrace.Sw.Info);

                // Form Authentication, we log the internal userId stored in local identification database
                if ( Config.AuthenticationMode == AuthenticationMode.Forms )
                {
                    AddonNiceIdentity  Idt          =   PortalSettings.CurrentIdentity;
                    if ( !PortalSettings.IsCurrentUserNull &&
                        !string.IsNullOrEmpty(PortalSettings.CurrentIdentity.Name) )
                    {
                        AddonNiceMembershipUser usr =   (AddonNiceMembershipUser)Membership.GetUser(Idt.Name);
                        if ( usr != null )
                        {
                            if ( AuthenticationTrace.Sw.TraceVerbose )
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DefaultModulesPage Page_Load portalID: {0}, Name: {1}, CustomerId: {2}",portalSettings.PortalID,usr.UserName,usr.CustomerId),AuthenticationTrace.Sw.Info);
                            OnPageRequestEvent((Guid)usr.ProviderUserKey,usr.UserName,usr.CustomerId.typeCode,usr.CustomerId.CrmId,portalSettings.PortalID,PageID,usr.UserData,IsUnderCRM);
                        }
                        else // ???? TBC
                        {
                            OnPageRequestEvent(Idt.ProviderUserKey,Idt.Name,Idt.typeCode,Idt.CrmId,portalSettings.PortalID,PageID,Idt.AuthenticationType,IsUnderCRM);
                        }
                    }
                    else
                    {
                        OnPageRequestEvent(Idt.ProviderUserKey,Idt.CrmImpersonateLogin,(int)CRMUtil.typeCode(CrmStr.systemuser),Wrapper.userId,portalSettings.PortalID,PageID,Idt.AuthenticationType,IsUnderCRM);
                    }
                }
                // Windows AD authentication, store the CrmId of the user stored in the principal
                else
                {
                    ADNCRMPrincipal p    =   PortalSettings.CurrentUser(false);
                    if ( AuthenticationTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DefaultModulesPage Page_Load authentication Windows portalID: {0}, Name: {1}, CrmId: {2}", 
                            portalSettings.PortalID,p.AddonNiceIdentity.Name,p.AddonNiceIdentity.CrmId),AuthenticationTrace.Sw.Info);
                    OnPageRequestEvent( Guid.Empty,p.Identity.Name,p.AddonNiceIdentity.typeCode, p.AddonNiceIdentity.CrmId, portalSettings.PortalID, PageID,p.AddonNiceIdentity.Name,IsUnderCRM);
                }
            }
            catch (Exception ex)
            {
                if ( PageTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SecureDefaultModulesPage Page_Load portalID: {0}, ex : {1}", portalSettings.PortalID, ex),PageTraceSwitch.Sw.Info);
                throw;
            }

        }

		public event PageRequestEventHandler PageRequestEvent;

		public void OnPageRequestEvent(Guid UID,int typeCode,Guid CRMID,int PID,int pgID,string userData,bool underCRM) 
		{
            bool isHandlerDefined   =   ( PageRequestEvent != null );
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage OnPageRequestEvent isHandlerDefined: {0}, UID: {1}, CRMID: {2}, PID: {3}, pgID: {4}", new object[]{isHandlerDefined,UID,CRMID,PID,pgID}),PageTraceSwitch.Sw.Info);
			if ( isHandlerDefined )
				PageRequestEvent(new PageRequestEventArgs(UID,typeCode,CRMID,PID,pgID,userData,underCRM));
		}

        void InitLoadedCtl(Control ctl,string layoutPath)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage InitLoadedCtl BEG",PageTraceSwitch.Sw.Info);
			// we check the control has a unique id, needed to add telerik radajax support
            if ( PageTraceSwitch.Sw.TraceVerbose )
    			Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage InitLoadedCtl Control before change ID: {0}.", ctl.ID),PageTraceSwitch.Sw.Info);
			ctl.ID          =   portalSettings.CurrentLayout.Replace("/", "_").TrimStart(new char[]{'_'});
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage InitLoadedCtl Control after change ID: {0}.", ctl.ID),PageTraceSwitch.Sw.Info);
			LayoutPlaceHolder.Controls.Add(ctl);
            for (int i = 0; i < ctl.Controls.Count; i++)
            {
                Control pn  =   ctl.Controls[i];
                if (pn is IAddonNicePane)
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage InitLoadedCtl initialize IAddonNicePane Interface for : {0}.", pn.ID),PageTraceSwitch.Sw.Info);
                    // this triggers the loading of modules in respectives panes
                    ((IAddonNicePane)pn).InitPanes(this);
                    break; // only one allowed
                }
            }
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage InitLoadedCtl END",PageTraceSwitch.Sw.Info);
        }
		
        /// <summary>
		/// Send from PreInit to have correct application of themes and skins 
		/// </summary>
		private void LoadPage()
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage LoadPage BEG",PageTraceSwitch.Sw.Info);
            const string LAYOUT_BASE_PAGE   =   "DefaultModulesPage.ascx";
            string defaultLayoutPath        =   string.Concat(AddonNice.Design.PagesLayoutManager.GlobalLayoutsWebPath, "/Default/", LAYOUT_BASE_PAGE);
			string layoutPath				=	string.Empty;
			try
			{
				// also usefull to switch design for home page or other pages!
				layoutPath					=	string.Concat(portalSettings.PortalLayoutPath, LAYOUT_BASE_PAGE);
                if ( PageTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage LoadPage LoadControl : {0}.", layoutPath),PageTraceSwitch.Sw.Info);
                Control ctl					=   LoadControl(layoutPath);
                InitLoadedCtl(ctl,layoutPath);
			}
			catch(System.IO.FileNotFoundException ex)
			{
                if (PageTraceSwitch.Sw.TraceError)
                {
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SecureDefaultModulesPage LoadPage file : {0}, ex : {1}", layoutPath, ex), PageTraceSwitch.Sw.Info);
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SecureDefaultModulesPage LoadPage reverting to : {0}", defaultLayoutPath), PageTraceSwitch.Sw.Info);
                }
                try
                {
                    if ( PageTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage Loadpage retry LoadControl : {0}.", defaultLayoutPath),PageTraceSwitch.Sw.Info);
                    Control ctl					=   LoadControl(defaultLayoutPath);
                    InitLoadedCtl(ctl,defaultLayoutPath);
                }
                catch (Exception ex2)
                {
                    if ( PageTraceSwitch.Sw.TraceError )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]SecureDefaultModulesPage LoadPage defaultLayoutPath : {0}, ex : {1}", defaultLayoutPath, ex2),PageTraceSwitch.Sw.Info);
                    throw;
                }
			}
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage LoadPage END",PageTraceSwitch.Sw.Info);
		}
		
        #region Std Overrides

        /// <summary>
        /// We changed the normal order, the pagelayout is loaded in PreInit to get skins
		/// and have opportunity to load modules in OnPreInit,  having correct theming
		/// Page_Load event is just here in cas we want statistics
        /// </summary>
		protected override void OnPreInit(EventArgs e)
        {
            if (PageTraceSwitch.Sw.TraceVerbose)
            {
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage OnPreInit portalSettings null: {0}.", portalSettings == null ), PageTraceSwitch.Sw.Info);
                if (portalSettings != null)
                {
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage OnPreInit portalSettings.ActivePageSettings null: {0}.", portalSettings.ActivePageSettings == null), PageTraceSwitch.Sw.Info);
                    if (portalSettings.ActivePageSettings != null)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage OnPreInit portalSettings.ActivePageSettings: {0}.", portalSettings.ActivePageSettings.PageName), PageTraceSwitch.Sw.Info);
                }
            }
            // Ensure that the visiting user has access to the current page
            if (!AddonNice.Security.PortalSecurity.IsUserInRoles(portalSettings.ActivePageSettings.AuthorizedRoles))
            {
                PortalSecurity.AccessDenied();
            }
            else
            {
                LoadPage();
            }
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage OnInit BEG.",PageTraceSwitch.Sw.Info);
            InitializeComponent(); 
			base.OnInit(e);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]SecureDefaultModulesPage OnInit END.",PageTraceSwitch.Sw.Info);
        }

		private void InitializeComponent() 
		{
            Load                    +=  new System.EventHandler(this.Page_Load);
			// Monitor every DesktoDefault page_load event
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SecureDefaultModulesPage InitializeComponent IsMonitoring : {0}",IsMonitoring),PageTraceSwitch.Sw.Info);
			if ( IsMonitoring )
				PageRequestEvent	+=  new PageRequestEventHandler(InitApplication.MonInitObject.LogEntry);

        }

        #endregion
         * */
	}    
}